<?php
declare(strict_types=1);

namespace App\Activity\Task;

use App\Activity\Event\Group;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\RedisFactory;
use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;

/**
 * @Crontab(name="GroupTask", rule="*\/30 * * * * *", callback="task")
 * Class GroupTask
 * @package App\Activity\Task
 */
class GroupTask
{
    /**
     * @Inject
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    protected $redis;

    public function __construct()
    {
        $this->redis = $this->container->get(RedisFactory::class)->get('group');
    }

    public function task()
    {
        $iterator = null;
        while($data = $this->redis->hscan('group:timer', $iterator)) {
            if (!empty($data)) {
                $auto = config('crontab.auto', 6*3600);
                foreach ($data as $acId => $group) {
                    $info = json_decode($group, true);
                    // 活动结束
                    if (time() >= $info['end']) {
                        $this->eventDispatcher->dispatch(new Group($info['acId'], $info['need']));
                        $this->redis->hDel('group:timer', (string)$acId);
                    }
                    // 6小时自动成团
                    if ( ( time() >= ($info['begin'] + $auto)) && ($this->redis->hExists('group:timer', (string) $info['acId'])) ){
                        $info['begin'] = $info['begin'] + $auto;
                        $this->redis->hSet('group:timer', (string) $info['acId'], json_encode($info));
                        $this->eventDispatcher->dispatch(new Group($info['acId'], $info['need']));
                    }
                }
            }
        }

    }
}
